import time


def bug_connect(bug_task,user_info_by_realname,type):
    user_bug_counts = {}
    for bug_task_ in bug_task:
        # 检查tasks1中的'finishedBy（完成）'字段是否与tasks2中的'realname'字段匹配
        # print(task_1['finishedBy（完成）'])

        # 如果用户不在字典中，则添加该用户

        if bug_task_["resolvedBy"] and bug_task_["resolvedBy"] not in user_bug_counts:
            user_bug_counts[bug_task_["resolvedBy"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
        if bug_task_["assignedTo"] and bug_task_["assignedTo"]!="closed" and bug_task_["assignedTo"] not in user_bug_counts:
            user_bug_counts[bug_task_["assignedTo"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
        if bug_task_["openedBy"] and bug_task_["openedBy"] not in user_bug_counts:
            user_bug_counts[bug_task_["openedBy"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}

        if bug_task_["closedBy"] and  bug_task_["closedBy"] not in user_bug_counts:
            user_bug_counts[bug_task_["closedBy"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
        #指派
        if bug_task_["assignedTo"] and bug_task_["assignedTo"]!="closed" :
            user_bug_counts[bug_task_["assignedTo"]]['assignedTo'] += 1

        #已完成  #已完成： 完成人不空
        if bug_task_["resolvedBy"]:
            user_bug_counts[bug_task_["resolvedBy"]]['completed_bug'] += 1
        if bug_task_["closedBy"]:
            user_bug_counts[bug_task_["closedBy"]]['closed_bug'] += 1
        #未完成
        if bug_task_["assignedTo"] and bug_task_["assignedTo"]!="closed" and not bug_task_["closedBy"]:
            user_bug_counts[bug_task_["assignedTo"]]['uncompleted_bug'] += 1
        # if bug_task_["openedBy"] and not bug_task_["assignedTo"] and not bug_task_["resolvedBy"]:
        #     user_bug_counts[bug_task_["openedBy"]]['uncompleted_bug'] += 1
        if bug_task_["openedBy"]:
            # print('1',bug_task_["openedBy"])
            # print('2',user_bug_counts)
            user_bug_counts[bug_task_["openedBy"]]['submitted_bug'] += 1

    bug_new_ = []
    for user_,u_d in user_info_by_realname.items():

        if user_ in user_bug_counts:
            dict1 = u_d.copy()
            dict2 = user_bug_counts[user_]
            dict1.update(dict2)
            #print("dict1:",dict1)
        else:
            dict1 = u_d.copy()
            dict2= {"assignedTo":0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
            dict1.update(dict2)
            #print("dict1:", dict1)\

        if type in u_d["name"]:
            bug_new_.append(dict1)
            #print("dict1",dict1)


    return bug_new_
def calculate_defect_scores(defect_counts):
    department_defects = {}
    for dict_u in defect_counts:
        if dict_u["dept"] not in department_defects:
            department_defects[dict_u["dept"]] = []
        department_defects[dict_u["dept"]].append((dict_u["account"], dict_u["uncompleted_bug"],dict_u["assignedTo"]))

    # Calculate scores and ranks for each department
    user_scores_with_rank = []
    for department, users_defects in department_defects.items():
        #print(department, users_defects)
        # Sort the defects list in descending order for each department
        sorted_defects = sorted(users_defects, key=lambda x: x[1])
        # tem_rank = list(sorted(set([i for a, i,b in sorted_defects if not(i==b!=0)])))  # if i!=0
        tem_rank = list(sorted(set([i for a, i, b in sorted_defects if not (i == b != 0)])))  # if i!=0
        # print("sorted_defectstem_rank",tem_rank)

        for i, (name,uncompleted_bug,assignedTo) in enumerate(sorted_defects, start=1):

            dict_l = {}
            if uncompleted_bug in tem_rank:
                rank= tem_rank.index(uncompleted_bug)+1

            if 2 > len(tem_rank) >= 1:
                dict_l['score'] = 100
            elif len(tem_rank) == 2:
                if rank == 1:
                    dict_l['score'] = 100
                if rank == 2:
                    dict_l['score'] = 75
            elif len(tem_rank) == 3:
                if rank == 1:
                    dict_l['score'] = 100
                if rank == 2:
                    dict_l['score'] = 75
                if rank == 3:
                    dict_l['score'] = 50
            else:
                if uncompleted_bug ==assignedTo== 0 or  rank <= len(tem_rank) * 0.25 :
                    dict_l['score'] = 100
                elif rank <= len(tem_rank) *  0.5:
                    dict_l['score'] = 75
                elif rank <= len(tem_rank) * 0.75:
                    dict_l['score'] = 50
                elif rank <= len(tem_rank) * 1.0:
                    dict_l['score'] = 25
                else:
                    dict_l['score'] = 0
            if uncompleted_bug==assignedTo!=0:
                dict_l['score']=0
                rank=len(tem_rank)+1
            dict_l["name"] = name
            dict_l['rank'] = rank
            # if department=="财务金融事业部":
            #     print("财务金融事业部",dict_l["name"],dict_l['rank'],dict_l['score'],uncompleted_bug)
            # print("dict_l",dict_l)
            user_scores_with_rank.append(dict_l)

    for dict_u in defect_counts:
        for dict_l in user_scores_with_rank:
            if dict_u["account"] == dict_l['name']:
                dict_u["rank"] = dict_l["rank"]
                dict_u["score"] = dict_l["score"]

            # print(dict_u)

        #print(dict_u)

    return defect_counts


def not_close_bug(bug_task, user_tasks):
    # print("——————2未关闭缺陷数 25%————————")
    #step2 未关闭缺陷数 25%
    # import csv
    # bug_file = open('bug.csv', 'r')
    # bug_task = csv.DictReader(bug_file)
    # user_file = open('user.csv', 'r')
    # user_tasks = csv.DictReader(user_file)
    t1=time.time()
    user_info_by_realname = {task['account']: task for task in user_tasks}
    type="开发"
    bug_new = bug_connect(bug_task, user_info_by_realname,"开发")
    # 计算得分

    defect_scores = calculate_defect_scores(bug_new)

    return defect_scores

    # print(len(defect_scores))
    # print(time.time()-t1)
    # csv_filename = './未关闭缺陷数 25%.csv'
    # with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
    #     fieldnames = defect_scores[0].keys()
    #     print(fieldnames)
    #     writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    #     writer.writeheader()
    #     for user_data in defect_scores:
    #         writer.writerow(user_data)